//
//  WFMyFarmListViewController.m
//  WisdomFarm
//
//  Created by 心情 on 2017/10/26.
//  Copyright © 2017年 sky. All rights reserved.
//

#import "WFMyFarmListViewController.h"
#import "WFFarmRequest.h"
#import "WFLocationManager.h"
#import "WFFarmListHeaderView.h"
#import "UINavigationController+WFUtils.h"
#import "WFFarmListCellTableViewCell.h"
#import "WFFarmEditViewController.h"
#import "WFFarmDao.h"

@interface WFMyFarmListViewController ()<
WFFarmListCellTableViewCellDelegate,
WFRefreshProtocol
>

@property (nonatomic, strong) WFFarmListHeaderView *headerView;
@property (nonatomic, strong) UITableViewHeaderFooterView *sectionHeaderView;
@property (nonatomic, strong) UIButton *addButton;

@property (nonatomic, strong) NSArray<WFFarm *> *farms;
@property (nonatomic, assign) BOOL editing;


@end

@implementation WFMyFarmListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self wf_enableRefresh];
    
    self.title = @"选择农场";
    @weakify(self);
    [self editFinish];
    
    [self.tableView registerClass:[WFFarmListCellTableViewCell class] forCellReuseIdentifier:@"WFFarmListCellTableViewCell"];
    self.tableView.backgroundColor = [UIColor backgroundColor];
    self.tableView.rowHeight = 48;
    self.tableView.separatorColor = [UIColor separatorColor];

    self.headerView = [[WFFarmListHeaderView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 48)];
    [self.headerView.coverButton bk_addEventHandler:^(id sender) {
        @strongify(self);
        WFFarm *farm = [WFFarm new];
        CLLocation *currentLocation = [[WFCacheStore sharedCacheStore] currentLocation];
        farm.latitude = currentLocation.coordinate.latitude;
        farm.longitude = currentLocation.coordinate.longitude;
        farm.name = self.headerView.addressLabel.text;
        if (self.farmClickHandle) {
            self.farmClickHandle(farm);
        }
    } forControlEvents:UIControlEventTouchUpInside];
    self.tableView.tableHeaderView = self.headerView;

    self.addButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.addButton.frame = CGRectMake(0, 0, self.view.width, 48);
    self.addButton.backgroundColor = [UIColor contentBackgroundColor];
    self.addButton.titleLabel.font = SCFont(14);
    [self.addButton setImage:[UIImage imageNamed:@"home_edit_icon_plus"] forState:UIControlStateNormal];
    [self.addButton setTitle:@"添加新农场" forState:UIControlStateNormal];
    [self.addButton setTitleColor:[UIColor textLightColor] forState:UIControlStateNormal];
//MARK: 添加农场
    [self.addButton bk_addEventHandler:^(id sender) {
        @strongify(self);
        [self toFarmEditWithFarm:nil];
    } forControlEvents:UIControlEventTouchUpInside];
    self.tableView.tableFooterView = self.addButton;
    
    self.sectionHeaderView = [[UITableViewHeaderFooterView alloc] init];
    UIView *backgroundView = [[UIView alloc] init];
    self.sectionHeaderView.backgroundView = backgroundView;
    UILabel *titleLabel = [UILabel new];
    [self.sectionHeaderView addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.left.offset(23);
    }];
    titleLabel.text = @"选取农场";
    titleLabel.font = SCFont(12);
    titleLabel.textColor = [UIColor textContentColor];
    //显示定位
    [[WFLocationManager sharedManager] startUpdateLocationForAddress:^(NSString *address) {
        @strongify(self);
        self.headerView.isLocated = YES;
    }];
    //请求列表
    [self wf_refreshData];
}

//MARK:- refresh
- (UIScrollView *)mainScrollView {
    return self.tableView;
}

- (void)refreshDataWithCompletion:(void (^)(BOOL, NSError *))completion {
    [[WFFarmDao new] farmListByUserId:[WFStore currentUser].id completion:^(NSArray<WFFarm *> *farmList, NSError *error) {
        if (error) {
            [SVProgressHUD showInfoWithStatus:error.localizedDescription];
            return;
        }
        self.farms = farmList;
        [self.tableView reloadData];
        completion(NO, error);
    }];
}

//MARK:- event
- (void)onEdit {
    self.editing = YES;
    self.navigationItem.rightBarButtonItem = [self.navigationController wf_itemWithTitle:@"完成" handle:^(id sender) {
        [self editFinish];
    }];
    [self.tableView reloadData];
}

- (void)editFinish {
    self.editing = NO;
    self.navigationItem.rightBarButtonItem = [self.navigationController wf_itemWithTitle:@"编辑" handle:^(id sender) {
        [self onEdit];
    }];
    [self.tableView reloadData];
}

- (void)toFarmEditWithFarm:(WFFarm *)farm {
    @weakify(self);
    WFFarmEditViewController *controller = [WFFarmEditViewController new];
    controller.farmId = farm.id;
    controller.farmChangedHandler = ^{
        @strongify(self)
        [self.navigationController popViewControllerAnimated:YES];
        [self wf_refreshData];
    };
    [self.navigationController pushViewController:controller animated:YES];
}

//MARK:- tableview delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.farms.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 37;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return self.sectionHeaderView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WFFarm *farm = self.farms[indexPath.row];
    WFFarmListCellTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WFFarmListCellTableViewCell" forIndexPath:indexPath];
    cell.delegate = self;
    cell.titleLabel.text = farm.name;
    cell.customEdit = self.editing;
    cell.check = [farm.id isEqualToString:self.farmId];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    WFFarm *selectedFarm = self.farms[indexPath.row];
    if (self.editing) {
        [self toFarmEditWithFarm:selectedFarm];
    } else {
        if (self.farmClickHandle) {
            self.farmClickHandle(selectedFarm);
        }
    }
}

//MARK:- cell delegate
- (void)farmListCellTableViewCellOnDelete:(WFFarmListCellTableViewCell *)cell {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    if (!indexPath) {
        return;
    }
    WFFarm *selectedFarm = self.farms[indexPath.row];
    //删除农场
    if ([selectedFarm.uid isEqualToString:[WFStore currentUser].id]) {
        [[WFFarmDao new] deleteFarmByObjectId:selectedFarm.objectId completion:^(BOOL result, NSError *error) {
            [SVProgressHUD showErrorWithStatus:(result ? @"删除成功" : error.localizedDescription)];
            [self wf_refreshData];
        }];
    } else {
        [SVProgressHUD showErrorWithStatus:@"删除失败"];
    }
}

- (void)farmListCellTableViewCellOnEdit:(WFFarmListCellTableViewCell *)cell {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    if (!indexPath) {
        return;
    }
    WFFarm *selectedFarm = self.farms[indexPath.row];
    [self toFarmEditWithFarm:selectedFarm];
}

@end
